package com.hancher.common.base;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.multidex.MultiDex;

import com.alibaba.android.arouter.launcher.ARouter;
import com.hancher.common.androidutil.ApkInfoUtil;
import com.hancher.common.androidutil.LogUtil;
import com.hancher.common.burypoint.BuryPointUtil;
import com.hancher.common.javautil.EmptyUtil;
import com.jeremyliao.liveeventbus.LiveEventBus;
import com.jeremyliao.liveeventbus.logger.Logger;
import com.kongzue.dialogx.DialogX;
import com.kongzue.dialogx.style.KongzueStyle;
import com.tencent.mmkv.MMKV;

import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;

/**
 * 作者：Hancher
 * 时间：2020/1/9.
 * 邮箱：ytu_shaoweijie@163.com
 * 版本：v1.0
 * <p>
 * 说明：
 */
public abstract class BaseApplication extends Application {

    public static BaseApplication instance;

    public static BaseApplication getInstance() {
        return instance;
    }

    protected abstract void init();

    private static List<Activity> activities = new ArrayList<>();

    @Override
    public void onCreate() {
        super.onCreate();
        String processName = ApkInfoUtil.getProcessName(this);
        LogUtil.i("进程名:%s, debug版本:%s", processName, ApkInfoUtil.isApkInDebug(this));
        crashProcess();
        if (!TextUtils.isEmpty(processName) && !processName.contains(":")) {
            instance = this;
            MMKV.initialize(this);
            init();
            //设置为Kongzue主题
            DialogX.globalStyle = new KongzueStyle();
            recordActivity();
            initEventBus();
            arouterinit();
        }
    }

    private void initEventBus() {
        LiveEventBus.config()
                .enableLogger(true)
                .setLogger(new Logger() {
                    @Override
                    public void log(Level level, String msg) {
                        if (EmptyUtil.isNotEmpty(msg) && !msg.startsWith("下载进度")) {
                            LogUtil.v(msg);
                        }
                    }

                    @Override
                    public void log(Level level, String msg, Throwable th) {
                        LogUtil.e(msg, th);
                    }
                })
                .lifecycleObserverAlwaysActive(true)
                .autoClear(true);
    }

    /**
     * 异常报错拦截log
     */
    private void crashProcess() {
        Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
            @Override
            public void uncaughtException(@NonNull Thread thread, @NonNull Throwable throwable) {
                LogUtil.e(throwable);
                LogUtil.e("全埋点(异常)：" + throwable.getMessage());
                android.os.Process.killProcess(android.os.Process.myPid());
                System.exit(1);
            }
        });
    }

    private void arouterinit() {
        if (ApkInfoUtil.isApkInDebug()) {           // 这两行必须写在init之前，否则这些配置在init过程中将无效
            ARouter.openLog();     // 打印日志
            ARouter.openDebug();   // 开启调试模式(如果在InstantRun模式下运行，必须开启调试模式！线上版本需要关闭,否则有安全风险)
        }
        ARouter.init(this); // 尽可能早，推荐在Application中初始化
    }


    public void recordActivity() {
        registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
            @Override
            public void onActivityCreated(@NonNull Activity activity, @Nullable Bundle savedInstanceState) {
                activities.add(activity);
                printLifecycle("onCreate", activity);
            }

            @Override
            public void onActivityStarted(@NonNull Activity activity) {
                printLifecycle("onStart", activity);
            }

            @Override
            public void onActivityResumed(@NonNull Activity activity) {
                BuryPointUtil.changeListener(activity);
                printLifecycle("onResume", activity);
            }

            @Override
            public void onActivityPaused(@NonNull Activity activity) {
                printLifecycle("onPause", activity);
            }

            @Override
            public void onActivityStopped(@NonNull Activity activity) {
                printLifecycle("onStop", activity);
            }

            @Override
            public void onActivitySaveInstanceState(@NonNull Activity activity, @NonNull Bundle outState) {
                printLifecycle("onSaveInstanceState", activity);
            }

            @Override
            public void onActivityDestroyed(@NonNull Activity activity) {
                activities.remove(activity);
                printLifecycle("onDestroyed", activity);
            }
        });
    }

    public static void printLifecycle(String lifecycle, Activity activity) {
        if ("onResume".equals(lifecycle)) {
            LogUtil.i("全埋点(生命周期)：%s -- %s", activity.getClass().getName(), lifecycle);
        } else {
            LogUtil.v("全埋点(生命周期)：%s -- %s", activity.getClass().getName(), lifecycle);
        }
    }

    /**
     * 退出app
     */
    public static void finish() {
        for (Activity item : activities) {
            item.finish();
        }
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        // 多个dex
        MultiDex.install(this);
    }
}
